package com.zhentao.config;

import com.aliyun.ocr_api20210707.Client;
import com.aliyun.ocr_api20210707.models.RecognizeIdcardRequest;
import com.aliyun.ocr_api20210707.models.RecognizeIdcardResponse;
import com.aliyun.tea.TeaException;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.models.RuntimeOptions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.beans.factory.annotation.Value;

import java.io.InputStream;

/**
 * 阿里云OCR配置类
 * 用于身份证识别功能
 */
@Configuration
@ConfigurationProperties(prefix = "aliyun.ocr")
public class AliyunOcrConfig {

    private static final Logger logger = LoggerFactory.getLogger(AliyunOcrConfig.class);

    // 阿里云OCR配置属性
    @Value("${aliyun.ocr.endpoint:ocr-api.cn-hangzhou.aliyuncs.com}")
    private String endpoint;

    @Value("${aliyun.ocr.access-key-id:}")
    private String accessKeyId;

    @Value("${aliyun.ocr.access-key-secret:}")
    private String accessKeySecret;

    @Value("${aliyun.ocr.region-id:cn-hangzhou}")
    private String regionId;

    @Value("${aliyun.ocr.timeout:30000}")
    private Integer timeout;

    /**
     * 创建阿里云OCR客户端Bean
     * @return OCR客户端实例
     */
    @Bean
    public Client ocrClient() {
        try {
            Config config = new Config();

            // 如果配置了AK/SK，使用AK/SK方式
            if (accessKeyId != null && !accessKeyId.isEmpty() &&
                accessKeySecret != null && !accessKeySecret.isEmpty()) {
                config.setAccessKeyId(accessKeyId);
                config.setAccessKeySecret(accessKeySecret);
                logger.info("使用AK/SK方式初始化OCR客户端");
            } else {
                // 否则使用默认凭据链（推荐生产环境使用）
                com.aliyun.credentials.Client credential = new com.aliyun.credentials.Client();
                config.setCredential(credential);
                logger.info("使用默认凭据链初始化OCR客户端");
            }

            config.setEndpoint(endpoint);
            config.setRegionId(regionId);

            // 设置超时时间
            if (timeout != null && timeout > 0) {
                config.setReadTimeout(timeout);
                config.setConnectTimeout(timeout);
            }

            logger.info("OCR客户端初始化成功，endpoint: {}", endpoint);
            return new Client(config);

        } catch (Exception e) {
            logger.error("OCR客户端初始化失败", e);
            throw new RuntimeException("OCR客户端初始化失败", e);
        }
    }

    /**
     * 身份证识别服务
     * @param client OCR客户端
     * @param imageStream 图片输入流
     * @return 识别结果
     */
    public RecognizeIdcardResponse recognizeIdcard(Client client, InputStream imageStream) {
        try {
            RecognizeIdcardRequest request = new RecognizeIdcardRequest()
                    .setBody(imageStream);

            RuntimeOptions runtime = new RuntimeOptions();
            runtime.setReadTimeout(timeout);
            runtime.setConnectTimeout(timeout);

            RecognizeIdcardResponse response = client.recognizeIdcardWithOptions(request, runtime);
            logger.info("身份证识别成功");
            return response;

        } catch (TeaException error) {
            logger.error("身份证识别失败 - TeaException: {}", error.getMessage());
            logger.error("诊断地址: {}", error.getData().get("Recommend"));
            throw new RuntimeException("身份证识别失败: " + error.getMessage(), error);
        } catch (Exception error) {
            logger.error("身份证识别失败 - Exception: {}", error.getMessage(), error);
            throw new RuntimeException("身份证识别失败: " + error.getMessage(), error);
        }
    }

    // Getter和Setter方法
    public String getEndpoint() {
        return endpoint;
    }

    public void setEndpoint(String endpoint) {
        this.endpoint = endpoint;
    }

    public String getAccessKeyId() {
        return accessKeyId;
    }

    public void setAccessKeyId(String accessKeyId) {
        this.accessKeyId = accessKeyId;
    }

    public String getAccessKeySecret() {
        return accessKeySecret;
    }

    public void setAccessKeySecret(String accessKeySecret) {
        this.accessKeySecret = accessKeySecret;
    }

    public String getRegionId() {
        return regionId;
    }

    public void setRegionId(String regionId) {
        this.regionId = regionId;
    }

    public Integer getTimeout() {
        return timeout;
    }

    public void setTimeout(Integer timeout) {
        this.timeout = timeout;
    }
}
